import { post, get } from "../utils/request";
import { KEY_TOKEN, KEY_SPOT_ID } from "../constants/storage";

export function setSession(token) {
  let rs = false;
  try {
    wx.setStorageSync(KEY_TOKEN, token);
    rs = true;
  } catch (error) {}
  return rs;
}

export async function refreshSession(token) {
  let rs = false;
  try {
    const token = wx.getStorageSync(KEY_TOKEN);
    const res = await post("/auth/refresh", {
      refreshToken: token,
    });
    if (!res.error) {
      wx.setStorageSync(KEY_TOKEN, res);
      rs = true;
    }
  } catch (error) {}
  return rs;
}

/**
 * 退出登录
 * @returns
 */
export async function signOut() {
  let rs = false;
  try {
    await post("/auth/logout");
    wx.removeStorageSync(KEY_TOKEN);
    wx.removeStorageSync(KEY_SPOT_ID);
    // wx.clearStorageSync();
    rs = true;
  } catch (error) {}
  return rs;
}

/**
 * 获取登录信息
 * @returns
 */
export async function fetchUserInfo() {
  let user = null;
  try {
    const res = await get("/auth/profile");
    if (!res.error) {
      user = res.data.user;
    }
  } catch (error) {}
  return user;
}

// 微信登录
export async function authByWechat(code) {
  const requestRes = await post(
    "/auth/login-wechat",
    {
      code,
      type: "owner",
    },
    {
      loadingText: "登录中...",
    }
  );

  return requestRes;
}

// 发送验证码
export async function sendSmsCode(mobile) {
  const requestRes = await post(
    "/verify-code/send",
    {
      target: mobile,
      type: "LOGIN",
    },
    {
      loadingText: "发送中...",
    }
  );

  return requestRes;
}

// 手机号登录
export async function authByPhone(data = {}) {
  const { phone, code } = data;
  const requestRes = await post(
    "/auth/login-code",
    {
      phone,
      code,
      type: "owner",
    },
    {
      loadingText: "登录中...",
    }
  );

  return requestRes;
}

// 绑定手机号
export async function bindPhone(data = {}) {
  const { phone, code, openid } = data;
  const requestRes = await post(
    "/auth/bind-phone",
    {
      phone,
      verifyCode: code,
      openid,
    },
    {
      loadingText: "绑定中...",
    }
  );

  return requestRes;
}
